<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Controller\BaseAbstractController;
use App\Jwt\SelfJwt;
use Exception;
use Hyperf\Utils\Context;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;

class JwtParse implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var HttpResponse
     */
    protected $response;

    const CUSTOM_ATTR_KEY = 'self_user_info';
    const X_PUBLIC_ACCESS_TOKEN_KEY = 'X_Public_AccessToken';

    public function __construct(ContainerInterface $container, RequestInterface $request, HttpResponse $response)
    {
        $this->container = $container;
        $this->request = $request;
        $this->response = $response;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $token = $this->request->input(self::X_PUBLIC_ACCESS_TOKEN_KEY);
        if ($token) {
            try {
                $userData = SelfJwt::getUserData($token);
                if ($userData) {
                  $myRequest = $request->withAttribute(self::CUSTOM_ATTR_KEY, $userData);
                    Context::set(ServerRequestInterface::class,$myRequest);
                    return $handler->handle($myRequest);
                }
            } catch (Exception $e) {
//                return $this->response->json(
//                    BaseAbstractController::returnFailed('解析token失败 '.$e->getMessage())
//                );
            }
        }

        return $handler->handle($request);
    }
}